package com.common.util;

import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @describe: 主键工厂
 */
public class IdFactoryUtil {
    
    private static HashMap<String, AtomicInteger> cache  = new HashMap<String, AtomicInteger>(1);
    private static final ReentrantLock lock = new ReentrantLock();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");

    /**
     * 获取主键
     * @return
     * @throws Exception
     */
    public static String getId() {
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String[] ipArray = ip.split("\\.");

        final String lastTwoPhaseIp = StringUtils.leftPad(ipArray[2], 3, '0') + StringUtils.leftPad(ipArray[3], 3, '0');
        String tss = getTimeStampSequence();
        String id = tss + lastTwoPhaseIp;
        return id;
    }

    /**
     * 获取指定数量的id
     * @param amount : id数量
     */
    public static List<String> getIds(final int amount){
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String[] ipArray = ip.split("\\.");
        final String lastTwoPhaseIp = StringUtils.leftPad(ipArray[2], 3, '0') + StringUtils.leftPad(ipArray[3], 3, '0');

        List<String> list = new ArrayList<>(amount);
        for (int i = 0; i < amount; i++){
            String tss = getTimeStampSequence();
            String id =  tss + lastTwoPhaseIp;
            list.add(id);
        }
        return list;
    }

    private static String getTimeStampSequence() {
        String timestamp = null;
        String inc = null;
        lock.lock();
        try {
            timestamp = sdf.format(new Date());
            AtomicInteger value = cache.get(timestamp);
            if(value == null) {
                cache.clear();
                int defaultStartValue = 0;
                cache.put(timestamp, new AtomicInteger(defaultStartValue));
                inc = String.valueOf(defaultStartValue);
            } else {
                inc = String.valueOf(value.addAndGet(1));
            }
        } finally {
            lock.unlock();
        }
        return timestamp + StringUtils.leftPad(inc, 4, '0');
    }

}
